const { ethers } = require("hardhat");
const fs = require("fs");
const path = require("path");

async function main() {
  // 部署 Voting 合约
  const Voting = await ethers.getContractFactory("Voting");
  const voting = await Voting.deploy();
  await voting.waitForDeployment();

  const address = await voting.getAddress();
  console.log("Voting contract deployed to:", address);

  // 导出 ABI 和合约地址（方便前端对接）
  const artifact = await hre.artifacts.readArtifact("Voting");
  const frontendDir = path.resolve(__dirname, "../frontend/src/contracts");
  if (!fs.existsSync(frontendDir)) {
    fs.mkdirSync(frontendDir, { recursive: true });
  }
  fs.writeFileSync(
    path.join(frontendDir, "Voting.json"),
    JSON.stringify({ address, abi: artifact.abi }, null, 2)
  );
  console.log("ABI & address exported to frontend/src/contracts/Voting.json");
}

// Hardhat 推荐的脚本模式
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
